package com.chang.springsecurity.controller;

import com.chang.springsecurity.DTO.ResponseResult;
import com.chang.springsecurity.security.service.UserDetailsServiceImpl;
import com.chang.springsecurity.security.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequiredArgsConstructor
public class AuthController {

    private final AuthenticationManager authenticationManager;
    private final UserDetailsServiceImpl userDetailsService;
    private final JwtUtil jwtUtil;

    @PostMapping("/auth/login")
    public ResponseResult<LoginResponse> login(@RequestBody LoginRequest request) {
        request.toString();

        try {
            // 1. 触发 Spring Security 的认证流程（会调用 UserDetailsService + 密码比对）
            authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword())
            );
        } catch (BadCredentialsException e) {
            return ResponseResult.error(401, "用户名或密码错误");
        }

        // 2. 再次加载用户详情（确保用户存在且未被禁用）
        UserDetails userDetails = userDetailsService.loadUserByUsername(request.getUsername());

        // 3. 从 userDetails 中提取角色（假设 authorities 只有一个 ROLE）
        String role = userDetails.getAuthorities().stream()
                .findFirst()
                .map(Object::toString)
                .map(auth -> auth.replace("ROLE_", "")) // 去掉 Spring 默认前缀
                .orElse("USER");

        // 4. 生成 JWT Token
        String accessToken = jwtUtil.generateToken(request.getUsername(), role);

        // 5. 返回 Token（使用ResponseResult包装）
        return ResponseResult.success(new LoginResponse(accessToken));
    }

    // DTO：登录请求
    public static class LoginRequest {
        private String username;
        private String password;

        // getter / setter
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
        public String toString(){
            System.out.println("LoginRequest: " + username + " " + password);
            return null;
        }
    }

    // DTO：登录响应
    public static class LoginResponse {
        private String accessToken;

        public LoginResponse(String accessToken) {
            this.accessToken = accessToken;
        }

        public String getAccessToken() { return accessToken; }
    }
}